//
//  BegainAddressVC.m
//  saler-ios
//
//  Created by 王亚陆 on 17/6/2.
//  Copyright © 2017年 sayimba. All rights reserved.
//

#import "BegainAddressVC.h"
#import <ContactsUI/ContactsUI.h>
#import "BegainAddressChooseVC.h"
#import "Common.h"
@interface BegainAddressVC ()
<UITextFieldDelegate,
CNContactPickerDelegate
>
{
    UIImageView * nav;
    Common * com;
    RootViewController * TabBar;
    UILabel * begain;
    NSMutableDictionary * dataDic;
}
@property (nonatomic,strong) UIView * backview;
@property (nonatomic,strong) UIView * begainBackView;

@end

@implementation BegainAddressVC

- (void)viewDidLoad {
    [super viewDidLoad];
    nav = [self createNav:@"物流运输"];
    [self.view addSubview:nav];
    self.view.backgroundColor = UIviewBackColor;
    
    dataDic = [[NSMutableDictionary alloc]init];

    [dataDic setObject:@"" forKey:@"sname"];
    [dataDic setObject:@"" forKey:@"contact"];
    [dataDic setObject:@"" forKey:@"phone"];
    
    [self createUI];
}


-(void)createUI{
    
    _backview = [[UIView alloc]init];
    _backview.backgroundColor = WhiteColor;
    [self.view addSubview:_backview];
    [_backview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left).with.offset(10*kWidth);
        make.top.mas_equalTo(nav.mas_bottom).with.offset(10*kHeight);
        make.size.mas_equalTo(CGSizeMake(view_Width, 200*kHeight));
    }];
    
    UILabel * begainlabel = [UILabel createUIlabel:@"始发地" andFont:FontOfSize14 andColor:UIlabelColor];
    [_backview addSubview:begainlabel];
    [begainlabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_backview.mas_left).with.offset(25*kWidth);
        make.top.mas_equalTo(_backview.mas_top).with.offset(30*kHeight);
    }];
    
    begain = [UILabel createUIlabel:@"请输入起始地" andFont:FontOfSize14 andColor:UIbtnColor];
    [_backview addSubview:begain];
    [begain mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(begainlabel.mas_right).with.offset(35*kWidth);
        make.centerY.mas_equalTo(begainlabel.mas_centerY);
    }];
    UIView * lineView1= [[UIView alloc]init];
    lineView1.backgroundColor = LineColor;
    [_backview addSubview:lineView1];
    [lineView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(begain.mas_left);
        make.centerY.mas_equalTo(begain.mas_centerY).with.offset(15*kHeight);
        make.height.mas_equalTo(0.5*kHeight);
        make.right.mas_equalTo(_backview.mas_right);
    }];
    
    UIButton * begainBtn = [UIButton createUIbutton:@"" andFont:1 andColor:nil];
    [begainBtn addTarget:self action:@selector(pressBegainBtn) forControlEvents:UIControlEventTouchUpInside];
    [_backview addSubview:begainBtn];
    [begainBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(begain.mas_left);
        make.centerY.mas_equalTo(begain.mas_centerY);
        make.right.mas_equalTo(_backview.mas_right);
        make.height.mas_equalTo(40*kHeight);
    }];

    UILabel * namelabel = [UILabel createUIlabel:@"姓 名" andFont:FontOfSize14 andColor:UIlabelColor];
    [_backview addSubview:namelabel];
    [namelabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_backview.mas_left).with.offset(25*kWidth);
        make.top.mas_equalTo(begainlabel.mas_bottom).with.offset(50*kHeight);
    }];

    
    
    
    UITextField * namefield = [[Common shared] createField:@"请输入姓名" andTag:1 andFont:FontOfSize14];
    [namefield addTarget:self action:@selector(textFieldWithText:) forControlEvents:UIControlEventEditingChanged];
    [_backview addSubview:namefield];
    [namefield mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(begain.mas_left);
        make.centerY.mas_equalTo(namelabel.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(Main_Width/2, 25*kHeight));
    }];

    UIImageView * people = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"home_people"]];
    people.tag = 100;
    [_backview addSubview:people];
    [people mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_backview.mas_right).with.offset(-25*kWidth);
        make.centerY.mas_equalTo(namelabel.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(16*kWidth, 16*kHeight));
    }];

    UIButton * iphoneBtn = [UIButton createUIbutton:@"" andFont:1 andColor:nil];
    [iphoneBtn addTarget:self action:@selector(pressNumber) forControlEvents:UIControlEventTouchUpInside];
    [_backview addSubview:iphoneBtn];
    [iphoneBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_backview.mas_right).with.offset(-5*kWidth);
        make.centerY.mas_equalTo(namelabel.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(50*kWidth, 40*kHeight));
    }];

    
    UIView * lineView2= [[UIView alloc]init];
    lineView2.backgroundColor = LineColor;
    [_backview addSubview:lineView2];
    [lineView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(namefield.mas_left);
        make.centerY.mas_equalTo(namelabel.mas_centerY).with.offset(15*kHeight);
        make.height.mas_equalTo(0.5*kHeight);
        make.right.mas_equalTo(_backview.mas_right);
    }];

    
    UILabel * iphonelabel = [UILabel createUIlabel:@"电 话" andFont:FontOfSize14 andColor:UIlabelColor];
    [_backview addSubview:iphonelabel];
    [iphonelabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_backview.mas_left).with.offset(25*kWidth);
        make.top.mas_equalTo(namelabel.mas_bottom).with.offset(50*kHeight);
    }];

    UITextField * iphonefield = [[Common shared] createField:@"请输入电话" andTag:2 andFont:FontOfSize14];
    [iphonefield addTarget:self action:@selector(textFieldWithText:) forControlEvents:UIControlEventEditingChanged];

    [_backview addSubview:iphonefield];
    [iphonefield mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(begain.mas_left);
        make.centerY.mas_equalTo(iphonelabel.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(Main_Width/2, 25*kHeight));
    }];

    
    UIView * lineView3= [[UIView alloc]init];
    lineView3.backgroundColor = LineColor;
    [_backview addSubview:lineView3];
    [lineView3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(iphonefield.mas_left);
        make.centerY.mas_equalTo(iphonelabel.mas_centerY).with.offset(15*kHeight);
        make.height.mas_equalTo(0.5*kHeight);
        make.right.mas_equalTo(_backview.mas_right);
    }];

    
    UIButton * nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [nextBtn setTitle:@"保存" forState:UIControlStateNormal];
    [nextBtn setTitleColor:WhiteColor forState:UIControlStateNormal];
    [nextBtn addTarget:self action:@selector(pressKeepBtn) forControlEvents:UIControlEventTouchUpInside];
    nextBtn.layer.cornerRadius = 5;
    nextBtn.layer.borderWidth = 0.5;
    nextBtn.layer.borderColor = YellowColor.CGColor;
    nextBtn.backgroundColor = YellowColor;
    [self.view addSubview:nextBtn];
    [nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(355*kWidth, 50*kHeight));
        make.top.mas_equalTo(_backview.mas_bottom).with.offset(37*kHeight);
    }];

}


-(void)pressBegainBtn{
    
    
    BegainAddressChooseVC * address = [[BegainAddressChooseVC alloc]init];
    
    address.callBackAddress = ^(NSMutableDictionary * dic){
        
        
//        code = 350100;
//        id = 350100;
//        initialWords = "<null>";
//        level = "<null>";
//        name = "<null>";
//        parentCode = "<null>";
//        path = "350000,350100";
//        pinyin = "<null>";
//        sname = "\U798f\U5dde\U5e02";
//        status = "<null>";

        
        begain.text = dic[@"sname"];
        begain.textColor = littleBlackColor;
        
        [dataDic setObject:dic[@"code"] forKey:@"code"];
        [dataDic setObject:dic[@"id"] forKey:@"id"];
        [dataDic setObject:dic[@"sname"] forKey:@"sname"];
    };
    
    [self.navigationController pushViewController:address animated:YES];
}

-(void)pressNumber{
    
    
    //让用户给权限,没有的话会被拒的各位
    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    if (status == CNAuthorizationStatusNotDetermined) {
        CNContactStore *store = [[CNContactStore alloc] init];
        [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (error) {
                NSLog(@"weishouquan ");
            }else
            {
                NSLog(@"chenggong ");//用户给权限了
                CNContactPickerViewController * picker = [CNContactPickerViewController new];
                picker.delegate = self;
                picker.displayedPropertyKeys = @[CNContactPhoneNumbersKey];//只显示手机号
                [self presentViewController: picker  animated:YES completion:nil];
            }
        }];
    }
    
    if (status == CNAuthorizationStatusAuthorized) {//有权限时
        CNContactPickerViewController * picker = [CNContactPickerViewController new];
        picker.delegate = self;
        picker.displayedPropertyKeys = @[CNContactPhoneNumbersKey];
        [self presentViewController: picker  animated:YES completion:nil];
    }
    else{
        
//        NSURL *url = [NSURL URLWithString:@"App-prefs:root=ACCOUNT_SETTINGS"];
//        
//        
//        if ([[UIApplication sharedApplication] canOpenURL:url]) {
//            
//            [[UIApplication sharedApplication] openURL:url];
//            
//        }
        
        [self createUIAlertController:@"您未开启通讯录权限,请前往设置-隐私-通讯录开启"];
    }
}

-(void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact{
    
    CNPhoneNumber * num = nil;
    NSString * name = nil;
    NSString * number = nil;
    
    if (contact.phoneNumbers.count >0) {
        num = contact.phoneNumbers[0].value;
        name = [NSString stringWithFormat:@"%@%@",contact.familyName,contact.givenName];
        number = [NSString stringWithFormat:@"%@",[num valueForKey:@"digits"]];
        UIImageView * image = [_backview viewWithTag:100];
        image.image = [UIImage imageNamed:@"people"];
        

    }else{
        
        name = [NSString stringWithFormat:@"%@%@",contact.familyName,contact.givenName];
        number = @"";
    }

    UITextField * field0 = (UITextField*)[_backview viewWithTag:1 ];
    UITextField * field1 = (UITextField*)[_backview viewWithTag:2];
    field0.text = name;
    field1.text = number;
    
    
    [dataDic setObject:name forKey:@"contact"];
    [dataDic setObject:number forKey:@"phone"];

}



-(void)textFieldWithText:(UITextField *)textField{
    //500 501 502 503
    UITextField * field = (UITextField*)textField;
    switch (textField.tag) {
        case 1://联系人
            if ([self textField:field shouldChangeCharactersInRange:NSMakeRange(0, 0) replacementString:@""]) {

                [dataDic setValue:field.text forKey:@"contact"];
                
            }
            break;
        case 2: //联系电话
            if ([self textField:field shouldChangeCharactersInRange:NSMakeRange(0, 0) replacementString:@""]) {
                
                [dataDic setValue:field.text forKey:@"phone"];

            }
            break;

        default:
            break;
    }

}


-(void)pressKeepBtn{
    

    NSString * contact = [NSString stringWithFormat:@"%@",dataDic[@"contact"]];
    NSString * begainAddress = [NSString stringWithFormat:@"%@",dataDic[@"sname"]];

    BOOL contactNO = NO;
    if (contact.length > 0 && begainAddress.length > 0) {
        
        contactNO = YES;
    }
    NSString * phone = [NSString stringWithFormat:@"%@",dataDic[@"phone"]];

    if ([Common validateUserPhone:phone] && contactNO) {
        if(_callBackInfor){
            _callBackInfor(dataDic);
        }
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [self createUIAlertController:@"请填写正确信息"];
    }
}

//触摸方法
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{
    for (UITextField * field in self.view.subviews) {
        [field resignFirstResponder];
    }
}

//点击return按钮 键盘隐藏 这是协议中的方法
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    //键盘隐藏 也就是让键盘取消第一响应者身份
    [textField resignFirstResponder];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{  //string就是此时输入的那个字符textField就是此时正在输入的那个输入框返回YES就是可以改变输入框的值NO相反
    
    if ([string isEqualToString:@"\n"])  //按会车可以改变
    {
        return YES;
    }
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
    
    if (textField.tag == 1) {
        
        if ([toBeString length] >25) {
            [self createUIAlertController:@"联系人输入不能超过25个字符"];
            return NO;
        }
    }else{
        

        if ([toBeString length] >11) {
            [self createUIAlertController:@"联系电话输入不能超过11个字符"];
            return NO;
        }

    }
    
    return YES;
}

-(void)createUIAlertController:(NSString*)title

{
    UIAlertController * alert =[UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * action =[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction * action1 =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:action1];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
